import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { User, Role, Team, Department } from '@/types/rbac';
import { userApi, UserListParams, CreateUserRequest, UpdateUserRequest } from '@/services/cloud/api/userApi';
import { roleApi } from '@/services/cloud/api/roleApi';
import { departmentApi } from '@/services/cloud/api/departmentApi';
import { teamApi } from '@/services/cloud/api/teamApi';

// 用户表单数据类型
export interface UserFormData {
  id?: string; // 更新时需要
  account: string;
  username: string;
  email: string;
  password?: string;
  realName?: string;
  phone?: string;
  roleIds: string[];
  teamIds: string[];
  departmentIds: string[];
  status: number;
  gender?: number;
  age?: number;
  description?: string;
}

// 用户查询参数类型
export interface UserQueryParams {
  keyword?: string;
  status?: number;
  departmentId?: number;
  roleId?: number;
  current?: number;
  size?: number;
}

// 综合用户管理hook
export const useUsers = () => {
  // 用户列表状态
  const [users, setUsers] = useState<User[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  
  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  // 搜索和筛选状态
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<number | undefined>();
  
  // 选项数据状态
  const [availableRoles, setAvailableRoles] = useState<Role[]>([]);
  const [availableTeams, setAvailableTeams] = useState<Team[]>([]);
  const [availableDepartments, setAvailableDepartments] = useState<Department[]>([]);
  const [optionsLoading, setOptionsLoading] = useState(false);

  // 加载用户列表
  const loadUsers = useCallback(async (params?: Partial<UserQueryParams>) => {
    try {
      setLoading(true);
      const queryParams: UserListParams = {
        current: pagination.current,
        size: pagination.pageSize,
        keyword: searchText,
        status: statusFilter,
        ...params,
        departmentId: params?.departmentId,
        roleId: params?.roleId,
      };
      
      const response = await userApi.getUsers(queryParams);
      setUsers(response.records || []);
      setTotal(response.total || 0);
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
      setUsers([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, searchText, statusFilter]);

  // 加载选项数据
  const loadOptions = useCallback(async () => {
    try {
      setOptionsLoading(true);
      const response = await userApi.getUserAssignmentData();
      setAvailableRoles(response.roles || []);
      setAvailableTeams(response.teams || []);
      setAvailableDepartments(response.departments || []);
    } catch (error) {
      console.error('获取选项数据失败:', error);
      message.error('获取选项数据失败');
    } finally {
      setOptionsLoading(false);
    }
  }, []);

  // 创建用户
  const createUser = useCallback(async (userData: UserFormData) => {
    try {
      const createData: CreateUserRequest = {
        ...userData,
        password: userData.password || '',
      };
      await userApi.createUser(createData);
      message.success('创建用户成功');
      await loadUsers();
    } catch (error) {
      console.error('创建用户失败:', error);
      message.error('创建用户失败');
      throw error;
    }
  }, [loadUsers]);

  // 更新用户
  const updateUser = useCallback(async (userData: UserFormData) => {
    if (!userData.id) {
      throw new Error('用户ID不能为空');
    }
    try {
      const updateData: UpdateUserRequest = {
        ...userData,
      };
      await userApi.updateUser(updateData);
      message.success('更新用户成功');
      await loadUsers();
    } catch (error) {
      console.error('更新用户失败:', error);
      message.error('更新用户失败');
      throw error;
    }
  }, [loadUsers]);

  // 删除用户
  const deleteUser = useCallback(async (userId: string) => {
    try {
      await userApi.deleteUser(userId);
      message.success('删除用户成功');
      await loadUsers();
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
      throw error;
    }
  }, [loadUsers]);

  // 批量删除用户
  const batchDeleteUsers = useCallback(async (userIds: string[]) => {
    try {
      await userApi.batchDeleteUsers(userIds);
      message.success(`成功删除 ${userIds.length} 个用户`);
      await loadUsers();
    } catch (error) {
      console.error('批量删除用户失败:', error);
      message.error('批量删除用户失败');
      throw error;
    }
  }, [loadUsers]);

  // 切换用户状态
  const toggleUserStatus = useCallback(async (userId: string, status: number) => {
    try {
      await userApi.toggleUserStatus(userId, status);
      const statusText = status === 1 ? '启用' : status === 0 ? '禁用' : '锁定';
      message.success(`用户已${statusText}`);
      await loadUsers();
    } catch (error) {
      console.error('切换用户状态失败:', error);
      message.error('切换用户状态失败');
      throw error;
    }
  }, [loadUsers]);

  // 重置密码
  const resetPassword = useCallback(async (userId: string) => {
    try {
      await userApi.resetPassword({ userId, newPassword: '123456' });
      message.success('密码重置成功，新密码为：123456');
    } catch (error) {
      console.error('重置密码失败:', error);
      message.error('重置密码失败');
      throw error;
    }
  }, []);

  // 搜索处理
  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 状态筛选处理
  const handleStatusFilter = useCallback((status: number | undefined) => {
    setStatusFilter(status);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 分页处理
  const handlePaginationChange = useCallback((current: number, pageSize: number) => {
    setPagination({ current, pageSize });
  }, []);

  // 重置筛选条件
  const resetFilters = useCallback(() => {
    setSearchText('');
    setStatusFilter(undefined);
    setPagination({ current: 1, pageSize: 10 });
  }, []);

  // 刷新数据
  const refresh = useCallback(() => {
    loadUsers();
  }, [loadUsers]);

  // 初始化数据
  useEffect(() => {
    loadUsers();
    loadOptions();
  }, []);

  // 当搜索条件或分页变化时重新加载数据
  useEffect(() => {
    loadUsers();
  }, [loadUsers]);

  return {
    // 状态
    users,
    total,
    loading,
    optionsLoading,
    pagination,
    searchText,
    statusFilter,
    availableRoles,
    availableTeams,
    availableDepartments,
    
    // 操作方法
    loadUsers,
    createUser,
    updateUser,
    deleteUser,
    batchDeleteUsers,
    toggleUserStatus,
    resetPassword,
    
    // 工具方法
    handleSearch,
    handleStatusFilter,
    handlePaginationChange,
    resetFilters,
    refresh,
  };
};

// 用户详情管理hook
export const useUser = (id?: string) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchUser = useCallback(async (userId: string) => {
    try {
      setLoading(true);
      const response = await userApi.getUser(userId);
      setUser(response || null);
    } catch (error) {
      console.error('获取用户详情失败:', error);
      message.error('获取用户详情失败');
      setUser(null);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (id) {
      fetchUser(id);
    }
  }, [id, fetchUser]);

  return {
    user,
    loading,
    refresh: () => id && fetchUser(id),
  };
};

// 用户统计hook
export const useUserStats = () => {
  const [stats, setStats] = useState({
    total: 0,
    active: 0,
    inactive: 0,
    locked: 0,
    online: 0,
  });
  const [loading, setLoading] = useState(false);

  const loadStats = useCallback(async () => {
    try {
      setLoading(true);
      const userStats = await userApi.getUserStats();
      setStats({
        total: userStats.totalUsers || 0,
        active: userStats.activeUsers || 0,
        inactive: userStats.inactiveUsers || 0,
        locked: (userStats.totalUsers || 0) - (userStats.activeUsers || 0) - (userStats.inactiveUsers || 0),
        online: Math.floor(Math.random() * (userStats.activeUsers || 10)) + 1,
      });
    } catch (error) {
      console.error('加载用户统计失败:', error);
      setStats({
        total: 0,
        active: 0,
        inactive: 0,
        locked: 0,
        online: 0,
      });
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadStats();
  }, [loadStats]);

  return {
    stats,
    loading,
    refresh: loadStats,
  };
};